﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SectorPoint.Net.Mail;

namespace Pop3Demo
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
			popClient = null;
		}

		Pop3Client popClient;

		void listViewMessages_ItemActivate( object sender, EventArgs e )
		{
			toolStripStatusLabel.Text = "Downloading message...";
			Application.DoEvents();
			int messageNumber = Convert.ToInt32( listViewMessages.SelectedItems[0].SubItems[0].Text );
			TextBoxLog.Text = "Message Headers:\r\n";
			foreach (string s in popClient.MailMessages[0].Headers.AllKeys)
			{
				TextBoxLog.Text += String.Format( "{0}: {1}\r\n", s, popClient.MailMessages[messageNumber].Headers[s] );
			}

			TextBoxLog.Text = "\r\n\r\nMessage Body:\r\n";
			TextBoxLog.Text = popClient.MailMessages[messageNumber].Body;
			toolStripStatusLabel.Text = null;
		}

		private void ButtonConnect_Click( object sender, EventArgs e )
		{
			toolStripStatusLabel.Text = "Connecting to POP3 server...";
			Application.DoEvents();
			
			// The next line establishes a connection to the POP3 server and attempts to authenticate using the supplied credentials
			popClient = new Pop3Client( textBoxHost.Text, Convert.ToInt32(textBoxPort.Text), textBoxUser.Text, textBoxPass.Text, checkBoxSsl.Checked );

			toolStripStatusLabel.Text = null;

			// The next line gets the number of messages in the maildrop.
			int messageCount = popClient.MailMessages.Count;
			
			TextBoxLog.Text = messageCount.ToString() + " messages in maildrop. Double-click a message to download it.";
			
			// This loops through each message and adds it to the List View.
			foreach (Pop3Message currentMessage in popClient.MailMessages)
			{
				listViewMessages.Items.Add( new ListViewItem( new string[] { currentMessage.MessageNumber.ToString(), currentMessage.MessageSize.ToString() } ) );
			}
		}
	}
}
